package com.guli.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.guli.common.to.esmodel.SkuEsModel;
import com.guli.common.utils.R;
import com.guli.common.constant.EsConstant;
import com.guli.search.feign.ProductFeign;
import com.guli.search.service.MallSearchSerive;
import com.guli.search.vo.SearchParam;
import com.guli.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.guli.common.constant.EsConstant.PRODUCT_PAGESIZE;

@Service
@Slf4j
public class MallSearchSeriveImpl implements MallSearchSerive {
    @Autowired
    private RestHighLevelClient esClient;
    @Autowired
    private ProductFeign productFeign;

    @Override
    public SearchResult search(SearchParam searchParam) {
        SearchResponse searchResponse = buildSearchRequest(searchParam);
        SearchResult searchResult = null;
        if (searchResponse != null) {
            log.info("{}", searchResponse);
            searchResult = buildSearchResult(searchResponse, searchParam);
        } else {
            log.info("查询es失败......");
        }
        return searchResult;
    }

    /*
     * 封装查询结果
     * */
    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {
        SearchResult searchResult = new SearchResult();
        List<SkuEsModel> skuEsModels = new ArrayList<>();
        SearchHits SearchHit = response.getHits();
        if (SearchHit != null) {
            for (SearchHit hit : SearchHit.getHits()) {
                String source = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(source, SkuEsModel.class);
                skuEsModels.add(skuEsModel);
            }
        }
        searchResult.setProduct(skuEsModels);
        //获取聚合categlogVos
        List<SearchResult.CatalogVo> cataglogVos = new ArrayList<>();
        ParsedLongTerms catalogAgg = response.getAggregations().get("category_agg");
        List<? extends Terms.Bucket> buckets = catalogAgg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVo cataglogVo = new SearchResult.CatalogVo();
            String key = bucket.getKeyAsString();
            cataglogVo.setCatalogId(Long.parseLong(key));
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("category_name_agg");
            List<? extends Terms.Bucket> buckets1 = catalog_name_agg.getBuckets();
            for (Terms.Bucket bucket1 : buckets1) {
                String key1 = bucket1.getKeyAsString();
                cataglogVo.setCatalogName(key1);
            }
            cataglogVos.add(cataglogVo);
        }
        searchResult.setCatalogs(cataglogVos);
        //获取聚合brands
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        List<? extends Terms.Bucket> brandAggBuckets = brand_agg.getBuckets();
        for (Terms.Bucket brandAggBucket : brandAggBuckets) {
            //获取品牌id
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            String keyAsString = brandAggBucket.getKeyAsString();
            brandVo.setBrandId(Long.parseLong(keyAsString));
            ParsedStringTerms brand_name_agg = brandAggBucket.getAggregations().get("brand_name_agg");
            //获取品牌名称
            for (Terms.Bucket bucket : brand_name_agg.getBuckets()) {
                String keyAsString1 = bucket.getKeyAsString();
                brandVo.setBrandName(keyAsString1);
            }
            //获取品牌图片
            ParsedStringTerms brand_img_agg = brandAggBucket.getAggregations().get("brand_img_agg");
            for (Terms.Bucket bucket : brand_img_agg.getBuckets()) {
                String keyAsString1 = bucket.getKeyAsString();
                brandVo.setBrandImg(keyAsString1);
            }
            brandVos.add(brandVo);
        }
        searchResult.setBrands(brandVos);
        //聚合属性attr
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        List<SearchResult.AttrVo> attrs = new ArrayList<>();
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attr = new SearchResult.AttrVo();
            String keyAsString = bucket.getKeyAsString();
            attr.setAttrId(Long.parseLong(keyAsString));
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            for (Terms.Bucket attrNameAggBucket : attr_name_agg.getBuckets()) {
                String keyAsString1 = attrNameAggBucket.getKeyAsString();
                attr.setAttrName(keyAsString1);
            }
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValues = new ArrayList<>();
            for (Terms.Bucket attrNameAggBucket : attr_value_agg.getBuckets()) {
                attrValues.add(attrNameAggBucket.getKeyAsString());
                attr.setAttrValue(attrValues);
            }
            searchResult.getAttrIds().add(Long.parseLong(keyAsString));
            attrs.add(attr);
        }
        searchResult.setAttrs(attrs);
        //buckets
        long total = SearchHit.getTotalHits().value;
        searchResult.setTotal(total);
        int totalPages = (int) (total % PRODUCT_PAGESIZE == 0 ? total / PRODUCT_PAGESIZE : (total / PRODUCT_PAGESIZE) + 1);
        searchResult.setTotalPages(totalPages);
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        searchResult.setPageNavs(pageNavs);
        //构造面包屑导航功能
        if (!CollectionUtils.isEmpty(param.getAttrs())) {
            List<SearchResult.NavVo> collect = param.getAttrs().stream().map(attr -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] strings = attr.split("_");
                navVo.setNavValue(strings[1]);
                R info = productFeign.info(Long.parseLong(strings[0]));
                SearchResult.AttrVo infoData = info.getData("attr", new TypeReference<SearchResult.AttrVo>() {
                });
                navVo.setNavName(infoData.getAttrName());
                //2、取消了这个面包屑以后，我们要跳转到哪个地方，将请求的地址url里面的当前置空
                //拿到所有的查询条件，去掉当前
                String encode = null;
                try {
                    encode = URLEncoder.encode(attr, "UTF-8");
                    encode.replace("+", "%20");  //浏览器对空格的编码和Java不一样，差异化处理
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String replace = param.get_queryString().replace("&attr=" + attr, "");
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);
                return navVo;
            }).collect(Collectors.toList());
            searchResult.setNavs(collect);
        }

        return searchResult;
    }

    /*
     * 封装发送给es的DSL语句
     * */
    private SearchResponse buildSearchRequest(SearchParam searchParam) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //must模糊匹配
        if (!StringUtils.isEmpty(searchParam.getKeyWord())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyWord()));
        }
        //filter过滤
        if (searchParam.getCategoryId3() != null) {
            boolQuery.filter(QueryBuilders.termQuery("categoryId", searchParam.getCategoryId3()));
        }
        if (!CollectionUtils.isEmpty(searchParam.getBrandId())) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
        }
        //nested
        if (!CollectionUtils.isEmpty(searchParam.getAttrs())) {
            for (String attrStr : searchParam.getAttrs()) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] str = attrStr.split("_");
                String attrId = str[0];
                String[] attrValues = str[1].split(":");
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                NestedQueryBuilder nestedQuery = QueryBuilders
                        .nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        //hasStock
        if (searchParam.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termsQuery("hasStock", searchParam.getHasStock() == 1));
        }
        //range
        if (!StringUtils.isEmpty(searchParam.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] str = searchParam.getSkuPrice().split("_");
            if (str.length == 2) {
                //区间
                rangeQuery.gte(str[0]).lte(str[1]);
            } else if (str.length == 1) {
                if (searchParam.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(str[0]);
                }
                if (searchParam.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(str[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }
        //sort
        if (!StringUtils.isEmpty(searchParam.getSort())) {
            String sort = searchParam.getSort();
            String[] sortStr = sort.split("_");
            SortOrder order = sortStr[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            searchSourceBuilder.sort(sortStr[0], order);
        }
        //分页
        searchSourceBuilder.from((searchParam.getPageNum() - 1) * PRODUCT_PAGESIZE);
        searchSourceBuilder.size(PRODUCT_PAGESIZE);
        if (!StringUtils.isEmpty(searchParam.getKeyWord())) {
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            searchSourceBuilder.highlighter(builder);
        }
        //聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        //品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        searchSourceBuilder.aggregation(brand_agg);
        //分类聚合
        TermsAggregationBuilder category_agg = AggregationBuilders.terms("category_agg");
        category_agg.field("categoryId").size(10);
        category_agg.subAggregation(AggregationBuilders.terms("category_name_agg").field("categoryName").size(10));
        searchSourceBuilder.aggregation(category_agg);
        //
        NestedAggregationBuilder nested = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(10);
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(10));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(10));
        nested.subAggregation(attr_id_agg);
        searchSourceBuilder.aggregation(nested);
        searchSourceBuilder.query(boolQuery);
        System.out.println("构建DSL语句" + searchSourceBuilder);
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
        try {
            SearchResponse searchResponse = esClient.search(searchRequest, RequestOptions.DEFAULT);
            return searchResponse;
        } catch (IOException e) {
            log.error("DSL请求构建失败");
        }
        return null;
    }
}
